package org.gap.jseed.injection;

import static java.lang.String.format;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.gap.jseed.Injector;
import org.gap.jseed.SeedContainer;
import org.gap.jseed.injection.annotation.Inject;
import org.gap.jseed.injection.annotation.ServiceFactory;
import org.gap.jseed.reflect.MethodIterator;

public class ServiceFactoryInjectorFactory implements Injector {
	
	@Override
	public void inject(ClassWriter javaWriter, Class<?> javaClass) {
		if (Modifier.isAbstract(javaClass.getModifiers())) {
			MethodIterator iterator = new MethodIterator(javaClass);

			for (Method each : iterator) {
				injectMethods(javaWriter, each);
			}
		}
	}

	private void injectMethods(ClassWriter javaWriter, Method method) {
		for (Annotation each : method.getAnnotations()) {
			if (each.annotationType().equals(ServiceFactory.class)) {
				javaWriter.addSetterMethod("_jSeedContainer", SeedContainer.class, Inject.class);
				String classType = method.getReturnType().getName();
				javaWriter.writeBody(method, format("{ return (%s) _jSeedContainer.get(%s.class); }", classType, classType));
			}
		}
	}
}
